package com.example.im.service.impl;

import com.example.im.model.User;
import com.example.im.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean registerUser(User user) {
        try {
            String checkSql = "SELECT COUNT(*) FROM user WHERE username = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, user.getUsername());

            if (count != null && count > 0) {
                log.warn("注册失败 - 用户名已存在: {}", user.getUsername());
                return false;
            }

            String insertSql = "INSERT INTO user (username, password) VALUES (?, ?)";
            jdbcTemplate.update(insertSql, user.getUsername(), user.getPassword());
            log.info("用户注册成功: {}", user.getUsername());
            return true;

        } catch (DuplicateKeyException e) {
            log.error("用户名重复异常: {}", e.getMessage());
            return false;
        } catch (Exception e) {
            log.error("注册系统异常: {}", e.getMessage());
            throw new RuntimeException("注册失败", e);
        }
    }

    @Override
    public User loginUser(User user) {
        try {
            // 调试输出用户名和密码
            System.out.println("【调试】接收到的用户名: " + user.getUsername());
            System.out.println("【调试】接收到的密码: " + user.getPassword());

            String sql = "SELECT * FROM user WHERE username = ?";
            User dbUser = jdbcTemplate.queryForObject(
                    sql,
                    (rs, rowNum) -> {
                        User u = new User();
                        u.setUsername(rs.getString("username"));
                        u.setPassword(rs.getString("password"));
                        return u;
                    },
                    user.getUsername()  // 使用 user 对象中的 username
            );
            // 简单明文比对（若需加密存储，需额外处理）
            return dbUser != null && dbUser.getPassword().equals(user.getPassword()) ? dbUser : null;
        } catch (Exception e) {
            return null;
        }
    }

    // 根据用户名查询用户
    @Override
    public User getUserByUsername(String username) {
        try {
            String sql = "SELECT * FROM user WHERE username = ?";
            return jdbcTemplate.queryForObject(
                    sql,
                    (rs, rowNum) -> {
                        User u = new User();
                        u.setUsername(rs.getString("username"));
                        u.setPassword(rs.getString("password"));
                        return u;
                    },
                    username
            );
        } catch (Exception e) {
            return null;
        }
    }
}